
package com.shop.cloud.weixin.admin.controller;

import cn.binarywang.wx.miniapp.api.WxMaMediaService;
import com.shop.cloud.common.core.util.FileUtils;
import com.shop.cloud.common.core.util.R;
import com.shop.cloud.weixin.admin.config.ma.WxMaConfiguration;
import com.shop.cloud.weixin.common.constant.WxReturnCode;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * 小程序直播
 *
 * @author
 * @date 2019-03-23 21:26:35
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/wxmamedia")
@Tag(description = "wxmamedia", name = "小程序临时素材接口")
public class WxMaMediaController {

	/**
	 * 临时素材上传
	 * @param mulFile
	 * @return
	 */
	@Operation(summary = "临时素材上传")
	@PostMapping("/upload")
	public R imageUploadV3(@RequestParam("file") MultipartFile mulFile, @RequestParam("appId") String appId, @RequestParam("mediaType") String mediaType) throws IOException {
		WxMaMediaService wxMaMediaService = WxMaConfiguration.getMaService(appId).getMediaService();
		File file = FileUtils.multipartFileToFile(mulFile);
		try {
			WxMediaUploadResult wxMediaUploadResult = wxMaMediaService.uploadMedia(mediaType, file);
			return R.ok(wxMediaUploadResult);
		} catch (WxErrorException e) {
			e.printStackTrace();
			log.error("素材上传失败" + e.getMessage());
			return WxReturnCode.wxErrorExceptionHandler(e);
		}
	}

	/**
	 * 获取临时素材
	 * @param
	 * @return Base64
	 */
	@SneakyThrows
	@Operation(summary = "获取临时素材")
	@GetMapping("/{appid}/{mediaid}")
	public R getMedia(@PathVariable("appid") String appId, @PathVariable("mediaid") String mediaId) {
		try {
			WxMaMediaService wxMaMediaService = WxMaConfiguration.getMaService(appId).getMediaService();
			File file = wxMaMediaService.getMedia(mediaId);
			FileInputStream inputFile = new FileInputStream(file);
			byte[] buffer = new byte[(int)file.length()];
			inputFile.read(buffer);
			inputFile.close();
			String rs = new String(Base64.getEncoder().encode(buffer));
			return R.ok(rs);
		} catch (WxErrorException e) {
			e.printStackTrace();
			log.error("获取临时素材失败" + e.getMessage());
			return WxReturnCode.wxErrorExceptionHandler(e);
		}
	}
}
